package com.gopay.common.util.xml.xmlutils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;

import com.gopay.common.util.xml.constants.BeanType;
import com.gopay.common.util.xml.utils.Assert0;

/**
 * 
 * @author liujy
 * 
 */
public class XmlProFileTemplateCheck {

	private static final String SELECT_ELEMENT_BY_MESSAGE = "/messages/message";

	// private static final String SELECT_ATTRIBUTE_BY_MSGTYPE =
	// "/messages/message/@msgType";

	/**
	 * 验证文件合规检查
	 * 
	 * @param document
	 * @return
	 */
	public static boolean isValidatorCheck(Document document) {
		if (document == null) {
			return true;
		}
		boolean flag = false;
		flag = checkFormName(document);
		if (!flag) {
			return false;
		}
		return true;
	}

	/**
	 * 验证formname是否重复
	 * 
	 * @param document
	 * @return
	 * @throws ValidatorTemplateCheckException
	 */
	@SuppressWarnings("unchecked")
	private static boolean checkFormName(Document document) {
		if (document == null) {
			return true;
		}
		Map<String, String> map = new HashMap<String, String>();
		List<Element> listME = document.selectNodes(SELECT_ELEMENT_BY_MESSAGE);
		if (listME == null || listME.size() == 0) {
			return true;
		}
		for (int i = 0, size = listME.size(); i < size; i++) {
			Element em = listME.get(i);
			String msgType = em.attributeValue("msgType");
			if (msgType == null || msgType.trim().length() == 0) {
				throw new RuntimeException(em.getName()
						+ ".msgType is invalid：" + msgType);
			}

			if (map.get(msgType) != null) {
				throw new RuntimeException("msgType is already exists："
						+ msgType);
			}

			map.put(msgType, msgType);
		}
		
		for (int i = 0, size = listME.size(); i < size; i++) {
			Element em = listME.get(i);
			List<Element> listBE = em.selectNodes("beans/bean");
			Assert0.notEmpty4List(
					listBE,
					"beans/bean/ must be not empty, msgType: "
							+ em.attributeValue("msgType"));
			boolean isMainExists = false;
			for (Element e : listBE) {
				Assert0.notNull(e, "beans/bean must be not null, msgType: " + em.attributeValue("msgType"));
				String path = e.attributeValue("path");
				String beanType = e.attributeValue("beanType");
				if(BeanType.beanTypeList.value.equals(beanType)){
					if(path == null || path.split("/").length < 1){
						throw new RuntimeException("beans/bean/@path is invalid, path: "+ path
								+ ", msgType:" + em.attributeValue("msgType") + ", beanType: list");
					}
				}else if(BeanType.beanTypeMain.value.equals(beanType)){
					if (isMainExists) {
						throw new RuntimeException(
								"beanType 'main' is exists, msgType:"
										+ em.attributeValue("msgType"));
					} else {
						isMainExists = true;
					}
				}else{
					throw new RuntimeException(
							"beanType 'main' is exists, msgType:"
									+ em.attributeValue("msgType"));
				}
			}
		}

		return true;
	}
}
